package redis

import (
	"cart_srv/cart"
	"context"
	"fmt"
	"strconv"
)

func AddCart(cart map[string]interface{}) error {
	key := fmt.Sprintf("cart:%d:%d", cart["user_id"], cart["good_id"])
	return Rdb.HMSet(context.Background(), key, cart).Err()
}

func GetExists(userId, goodId int64) bool {
	key := fmt.Sprintf("cart:%d:%d", userId, goodId)
	return Rdb.Exists(context.Background(), key).Val() == 1
}
func UpdateNumStock(userId, goodId, num int64) error {
	key := fmt.Sprintf("cart:%d:%d", userId, goodId)
	return Rdb.HIncrBy(context.Background(), key, "num", num).Err()
}

func StockDel(userId, goodId int64) error {
	key := fmt.Sprintf("cart:%d:%d", userId, goodId)
	return Rdb.Del(context.Background(), key).Err()
}

func CheckAllGood(userId, checked int) {
	key := fmt.Sprintf("cart:%d:*", userId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, s := range keys {
		Rdb.HSet(context.Background(), s, "checked", checked)
	}
	return
}

func CartTotal(userId int) (count int, amount float64) {
	key := fmt.Sprintf("cart:%d:*", userId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, s := range keys {
		goodAllMap := Rdb.HGetAll(context.Background(), s).Val()
		num, _ := strconv.Atoi(goodAllMap["num"])
		goodPrice, _ := strconv.ParseFloat(goodAllMap["good_price"], 64)
		checked, _ := strconv.Atoi(goodAllMap["checked"])

		if checked == 1 {
			count += num
			amount = goodPrice * float64(num)
		}
	}
	return
}
func CheckList(userId int64) (cartList []*cart.ListItem, err error) {
	key := fmt.Sprintf("cart:%d:*", userId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, s := range keys {
		goodList := Rdb.HGetAll(context.Background(), s).Val()
		userId, _ := strconv.Atoi(goodList["user_id"])
		goodId, _ := strconv.Atoi(goodList["good_id"])
		goodPrice, _ := strconv.ParseFloat(goodList["good_price"], 64)
		num, _ := strconv.Atoi(goodList["num"])
		checked := 1

		cartList = append(cartList, &cart.ListItem{
			UserId:    int64(userId),
			GoodId:    int64(goodId),
			Num:       int64(num),
			GoodTitle: goodList["good_title"],
			GoodPrice: float32(goodPrice),
			Checked:   int64(checked),
		})
	}
	return
}
func CartDel(userId int) {
	key := fmt.Sprintf("cart:%d:*", userId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, s := range keys {
		Rdb.Del(context.Background(), s)
	}
}

func CartCheck(userId, goodId, checked int64) {
	key := fmt.Sprintf("cart:%d:%d", userId, goodId)
	Rdb.HSet(context.Background(), key, "checked", checked)
	return
}

func CartYN(userId int64) bool {
	key := fmt.Sprintf("cart:%d:*", userId)
	return Rdb.Exists(context.Background(), key).Val() == 1
}
